package com.bhs.sansonglogistics.ui.home;

import static android.view.View.VISIBLE;
import static com.google.android.material.tabs.TabLayout.MODE_AUTO;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.viewpager2.widget.ViewPager2;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseFragment;
import com.bhs.sansonglogistics.bean.CompanyInfoBean;
import com.bhs.sansonglogistics.bean.Location;
import com.bhs.sansonglogistics.bean.OrderGoodsBean;
import com.bhs.sansonglogistics.bean.event.ListeningStatus;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.ui.enterprise.EnterpriseSettlementActivity;
import com.bhs.sansonglogistics.ui.order.HistoryOrderActivity;
import com.bhs.sansonglogistics.utils.SharedPreferencesUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bhs.sansonglogistics.view.SelectedFont3;
import com.google.android.material.badge.BadgeDrawable;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;

import okhttp3.ResponseBody;
import retrofit2.Response;


/**
 * 货源
 */
public class SourceGoodsFragment extends BaseFragment implements View.OnClickListener, NetCallBack {

    private TextView tvHistory;
    private TabLayout mTabLayout;
    private ViewPager2 mViewPage;
    private RelativeLayout mViewGroup;
    private FrameLayout mFlEnterpriseSettlement;
    private LinearLayout mLlListen;
    private ImageView mIvListen;
    private boolean listeningList;//是否听单
    private boolean isOpenVoice;//是否开启声音
    private TextView mTvStatus;
    private View mDot;
    private TextView mTvTitle;
    private View mMessageHint, mTopspeedHint;
    private int mPosition = 0;

    public static SourceGoodsFragment newInstance() {
        return new SourceGoodsFragment();
    }

    @Override
    public int initLayout() {
        return R.layout.fragment_source_goods;
    }


    @Override
    public void initView(View root) {
        //注册监听
        EventBus.getDefault().register(this);
        tvHistory = root.findViewById(R.id.tv_history);
        mTabLayout = root.findViewById(R.id.tabLayout);
        mViewPage = root.findViewById(R.id.view_page);
        tvHistory.setOnClickListener(this);
        mViewGroup = root.findViewById(R.id.viewGroup);
        mFlEnterpriseSettlement = root.findViewById(R.id.fl_enterprise_settlement);
        root.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getContext(), EnterpriseSettlementActivity.class));
            }
        });
        mFlEnterpriseSettlement.setOnClickListener(this);
        mLlListen = root.findViewById(R.id.ll_listen);
        mIvListen = root.findViewById(R.id.iv_listen);
//        mLlListen.setOnClickListener(this);
//        mIvListen.setOnClickListener(this);
        mTvStatus = root.findViewById(R.id.tv_status);
        mDot = root.findViewById(R.id.dot);
        mTvTitle = root.findViewById(R.id.tv_title);
        if (SharedPreferencesUtils.getString(getContext(), "urlType").equals("2")) {
            mTvTitle.setText("测试环境");
        }
        mMessageHint = root.findViewById(R.id.message_hint);
        mTopspeedHint = root.findViewById(R.id.topspeed_hint);
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initData() {
        isOpenVoice = SharedPreferencesUtils.getBoolean(getContext(), "voice", true);
        if (isOpenVoice) {
            mIvListen.setImageResource(R.mipmap.ic_listen);
        } else {
            mIvListen.setImageResource(R.mipmap.ic_mute);
        }
        mTabLayout.setTabMode(MODE_AUTO);
        //tab切换时候的字体设置
        mTabLayout.addOnTabSelectedListener(new SelectedFont3(activity));
        ArrayList<BaseFragment> fragments = new ArrayList<>();
        //2 极速单 1指派单
        fragments.add(SourceGoodsListFragment.newInstance(2));
        fragments.add(SourceGoodsListFragment.newInstance(1));

        mViewPage.setOffscreenPageLimit(fragments.size());
        mViewPage.setAdapter(new FragmentAdapter(activity, fragments));
        new TabLayoutMediator(mTabLayout, mViewPage, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(position == 0 ? "极速" : "指派");
            }
        }).attach();

        //boolean isOpenListening = SharedPreferencesUtils.getBoolean(getContext(), "isOpenListening", true);

        if (true) {
            mLlListen.performClick();
        }
        mViewPage.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                mPosition = position;
                if (position == 1) {
                    mMessageHint.setVisibility(View.GONE);
                } else {
                    mTopspeedHint.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);

    }

    @Subscribe
    public void onEvent(OrderGoodsBean event) {
        if (event.getOrder_type() == 1 && mPosition == 0) {
            mMessageHint.setVisibility(View.VISIBLE);
        }
        if (event.getOrder_type() == 2 && mPosition == 1) {
            mTopspeedHint.setVisibility(VISIBLE);
        }
    }

    @Override
    public void onResumes() {
        super.onResumes();
        networkRequest(netApi.getCompanyInfo(), this);
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.tv_history) {
            startActivity(new Intent(getActivity(), HistoryOrderActivity.class));
        } else if (id == R.id.ll_listen) {
            if (listeningList) {
                mLlListen.setBackgroundResource(R.drawable.border_grey_16);
                mTvStatus.setTextColor(Color.parseColor("#909399"));
                mDot.setBackgroundResource(R.drawable.bg_oval_grey);
                mTvStatus.setText("未听单");
                ToastUtil.show("已关闭听单");
                mIvListen.setVisibility(View.GONE);
            } else {
                mLlListen.setBackgroundResource(R.drawable.border_blue_16);
                mTvStatus.setTextColor(Color.parseColor("#485EF4"));
                mDot.setBackgroundResource(R.drawable.bg_oval_blue);
                mTvStatus.setText("听单中");
                ToastUtil.show("已开启听单");
                mIvListen.setVisibility(View.VISIBLE);
            }
            listeningList = !listeningList;
            EventBus.getDefault().post(new ListeningStatus(listeningList, isOpenVoice));
            SharedPreferencesUtils.saveBoolean(getContext(), "isOpenListening", listeningList);
        } else if (id == R.id.iv_listen) {
            if (isOpenVoice) {
                mIvListen.setImageResource(R.mipmap.ic_mute);
                ToastUtil.show("关闭声音");
            } else {
                mIvListen.setImageResource(R.mipmap.ic_listen);
                ToastUtil.show("开启声音");
            }
            isOpenVoice = !isOpenVoice;
            EventBus.getDefault().post(new ListeningStatus(listeningList, isOpenVoice));
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
        CompanyInfoBean infoBean = new Gson().fromJson(json, CompanyInfoBean.class);
        //入驻弹窗
        if (infoBean.isStatus()) {
            SharedPreferencesUtils.saveString(getContext(), "company_name", infoBean.getData().getCompany_info().getCompany_name());
            SharedPreferencesUtils.saveString(getContext(), "address", infoBean.getData().getCompany_info().getAddress());
            SharedPreferencesUtils.saveInt(getContext(), "logistics_id", infoBean.getData().getCompany_info().getLogistics_id());
            SharedPreferencesUtils.saveString(getContext(), "company_pic", infoBean.getData().getCompany_info().getCompany_pic());
            SharedPreferencesUtils.saveString(getContext(), "deposit_status", infoBean.getData().getCompany_info().getDeposit_status());
            Location.companyLat = Double.parseDouble(infoBean.getData().getCompany_info().getLatitude());
            Location.companyLon = Double.parseDouble(infoBean.getData().getCompany_info().getLongitude());
            if (infoBean.getData().getCompany_info().getPark_id() > 0) {
                mFlEnterpriseSettlement.setVisibility(View.GONE);
            } else {
                mFlEnterpriseSettlement.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onFailure(int requestCode) {

    }
}